<?php
require_once('../model/homeDao.php');
//展示首页
selectAllBoard();
selectAllArticle('hot');

//搜索功能
if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['type']) && $_GET['type'] == 'search') {
  // 判断文章cookie是否存在
  if (!isset($_COOKIE['wenzhang'])) {
    die("文章cookie值不存在");
  }

  // 先验证是否存在查询字符串
  $search = isset($_GET['search']) ? trim($_GET['search']) : '';
  $searchType = isset($_GET['searchtype']) ? $_GET['searchtype'] : '';
  $sort = isset($_GET['sort']) ? $_GET['sort'] : '';
  // 判断是否是文章cookie值
  if ($_COOKIE['wenzhang'] == 'true') {
    search($search, $searchType, 'lingshiSearchWz', 'wz', 'selectAllArticle', $sort);
  } elseif ($_COOKIE['wenzhang'] == 'false') {
    search($search, $searchType, 'lingshiSearch', 'bd', 'searchBoard', $sort);
  } else {
    die("文章cookie值不存在");
  }
}

function search($search, $searchType, $cookieName, $typeParam, $searchFunc, $sort)
{
  $message = ($typeParam == 'wz') ? '请输入搜索内容' : '请输入搜索板块';
  if ($search === '') {
    if ($typeParam == 'wz') {
      //文章控制搜索
      if (isset($_COOKIE[$cookieName]) && trim($_COOKIE[$cookieName]) !== '') {
        $searchFunc($sort, $_COOKIE[$cookieName]);
        echo "<script>alert('$message');window.location.href='../view/index.php?search=$_COOKIE[$cookieName]&searchtype=$typeParam&sort=$sort';</script>";
      } else {
        echo "<script>alert('$message');window.location.href='../view/index.php';</script>";
      }
    } else {
      //板块空值搜索
      if (isset($_COOKIE[$cookieName]) && trim($_COOKIE[$cookieName]) !== '') {
        $searchFunc($sort, $_COOKIE[$cookieName]);
        echo "<script>alert('$message');window.location.href='../view/index.php?search=$_COOKIE[$cookieName]&searchtype=$typeParam';</script>";
      } else {
        echo "<script>alert('$message');window.location.href='../view/index.php';</script>";
      }
    }

  } else {
    if ($typeParam == 'wz') {
      //文章有值搜索
      $searchFunc($sort, $search);
      setcookie($cookieName, $search);
      header("Location: ../view/index.php?search=" . $search . "&searchtype=$searchType" . "&sort=$sort");
      exit();
    } else {
      //板块有值搜索
      $searchFunc($search);
      setcookie($cookieName, $search);
      header("Location: ../view/index.php?search=" . $search . "&searchtype=$searchType");
      exit();
    }

  }
}



?>